package com.huacx.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.huacx.model.User;
import com.huacx.service.UserService;

@MultipartConfig
@Controller
@RequestMapping("/linkman")
public class LinkMan {
	@Resource
	private UserService userService;

	// 登录
	@RequestMapping("/login")
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		setMaxInactiveInterval
		HttpSession session = request.getSession();
		System.out.println("----session2: " + session.getId());

//        Object obj = session.getAttribute("user");
		String tel = request.getParameter("tel");
		String passwd = request.getParameter("passwd");
		JSONObject obj = new JSONObject();
		session.setAttribute("username", tel);

		System.out.println("----username: " + tel + " : " + "passwd: " + passwd);

		Map mp = new HashMap();
		mp.put("passwd", passwd);
		mp.put("tel", tel);
		String checkTel = userService.checkTel(tel);
		String res = userService.login(mp);
		System.out.println("---------res: " + res);
		if (checkTel == null) {
			obj.put("msg", "手机号[ " + tel + " ]未注册");
			obj.put("code", "400");
		} else {
			if (res != null) {
				obj.put("sessionId", session.getId());
				obj.put("username", res);
				obj.put("msg", "登录成功");
				obj.put("code", "200");
			} else {
				obj.put("msg", "密码错误");
				obj.put("code", "400");
			}
		}
		System.out.println("_____obj.toString(): " + obj.toString());
		response.getWriter().append(obj.toString());
	}

	// 查找所有数据
	@RequestMapping("/selectAllUser")
	public void selectAllUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();

		List<Map> li = new ArrayList<Map>();
		List<User> user = userService.selectAll();

		System.out.println("----------------user.size: " + user.size());
		for (int i = 0; i < user.size(); i++) {
			Map mp = new HashMap();
			String sex = user.get(i).getGender();
			String id = user.get(i).gettId() + "";
			String username = user.get(i).getUsername();
			String password = user.get(i).getPasswd();
			String tel = user.get(i).getTel() + "";

			System.out.println("----------data:" + "id:" + id + "&username:" + username + "&password:" + password
					+ "&sex:" + sex + "&tel:" + tel);

			mp.clear();
			mp.put("userid", id);
			mp.put("username", username);
			mp.put("password", password);
			mp.put("tel", tel + "");
			mp.put("sex", sex);
			System.out.println("**********map: " + mp.toString());
			li.add(mp);
		}
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	// 按ID查找
	@RequestMapping("/selectById")
	public void selectById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer t_id = 1;
		JSONObject obj = new JSONObject();
		List<Map> li = new ArrayList<Map>();
		List<User> user = userService.selectByPrimaryKey(t_id);
		System.out.println("----------------user.size: " + user.size());
		for (int i = 0; i < user.size(); i++) {
			Map mp = new HashMap();
			String sex = user.get(i).getGender();
			String id = user.get(i).gettId() + "";
			String username = user.get(i).getUsername();
			String password = user.get(i).getPasswd();
			String tel = user.get(i).getTel();

			System.out.println("----------data:" + "id:" + id + "&username:" + username + "&password:" + password
					+ "&sex:" + sex + "&tel:" + tel);

			mp.clear();
			mp.put("userid", id);
			mp.put("username", username);
			mp.put("password", password);
			mp.put("tel", tel + "");
			mp.put("sex", sex);
			System.out.println("**********map: " + mp.toString());
			li.add(mp);
		}
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	// 按电话查找
	@RequestMapping("/selectByTel")
	public void selectByTel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String tel = request.getParameter("tel");
		JSONObject obj = new JSONObject();
//			List<Map> li = new ArrayList<Map>();
		List<User> user = userService.selectByTel(tel);
		System.out.println("----------------user.size: " + user.size());
//			for (int i = 0; i < user.size(); i++) {
		Map mp = new HashMap();
		String id = user.get(0).gettId() + "";
		String username = user.get(0).getUsername();
		String password = user.get(0).getPasswd();
		String addr = user.get(0).getAddr();
		String gender = user.get(0).getGender();
		String work = user.get(0).getWork();
		String birthday = user.get(0).getBirthday();
//				String tel = user.get(i).getTel();

//				System.out.println("----------data:" + "id:" + id + "&username:" + username + "&password:" + password
//						+ "&sex:" + sex + "&tel:" + tel);

//				mp.clear();
		mp.put("userid", id);
		mp.put("username", username);
		mp.put("passwd", password);
		mp.put("tel", tel + "");
		mp.put("gender", gender);
		mp.put("addr", addr);
		mp.put("work", work);
		mp.put("birthday", birthday);
		System.out.println("**********map: " + mp.toString());
//				li.add(mp);
//			}
		obj.put("data", mp);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	// 分页查找
	@RequestMapping("/selectByPage")
	public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String searchVal = request.getParameter("searchVal");
		int count = Integer.parseInt(request.getParameter("count"));

		int pageNum = (Integer.parseInt(request.getParameter("pageNum")) - 1) * count;
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		Map searchMap = new HashMap();
		searchMap.put("searchVal", searchVal);
		searchMap.put("pageNum", pageNum);

		JSONObject obj = new JSONObject();
		List<Map> li = new ArrayList<Map>();
//		List<User> user = userService.selectByPrimaryKey();
		List<User> user = userService.selectByPage(searchMap);
		System.out.println("----------------user.size: " + user.size());
		for (int i = 0; i < user.size(); i++) {
			Map mp = new HashMap();

			String id = user.get(i).gettId() + "";
			String username = user.get(i).getUsername();
			String passwd = user.get(i).getPasswd();
			String addr = user.get(i).getAddr();
			String tel = user.get(i).getTel() + "";
			String gender = user.get(i).getGender();
			String work = user.get(i).getWork();
//			String birthday = formatter.format(user.get(i).getBirthday());
			String birthday = user.get(i).getBirthday() + "";
			System.out.println(
					"----------data:" + "t_id : " + id + "username: " + username + "passwd: " + passwd + "addr: " + addr
							+ "tel: " + tel + "gender: " + gender + "work: " + work + "birthday: " + birthday);

			mp.clear();
			mp.put("id", id);
			mp.put("username", username);
			mp.put("passwd", passwd);
			mp.put("tel", tel);
			mp.put("addr", addr);
			mp.put("work", work);
			mp.put("gender", gender);
			mp.put("birthday", birthday);
			System.out.println("**********map: " + mp.toString());
			li.add(mp);
		}
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("count", user.size());
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	// 注册
	@RequestMapping("/register")
	public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		JSONObject obj = new JSONObject();

		String userName = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String tel = request.getParameter("tel");
		String birthday = request.getParameter("birthday");
		String gender = request.getParameter("gender");
		String addr = request.getParameter("addr");
		String work = request.getParameter("work");

		String year = String.valueOf(date.get(Calendar.YEAR));
		String nMonth = String.valueOf(date.get(Calendar.MONTH));
		String nDay = String.valueOf(date.get(Calendar.DATE));
		int age = Integer.parseInt(year) - Integer.parseInt(birthday.split("-")[0]);// 当前年份-出生年份
		int month = Integer.parseInt(nMonth) - Integer.parseInt(birthday.split("-")[1]);// 当前月份-出生月份
		int day = Integer.parseInt(nDay) - Integer.parseInt(birthday.split("-")[2]);// 当前日-出生日
		if (month < 0) {
			age += 1;
		} else if (month == 0) {
			if (day < 0) {
				age += 1;
			}
		}

		System.out.println("---------" + userName + " : " + passwd + " : " + tel + " : " + birthday + " : " + age
				+ " : " + gender);
//		User user = new User(userName, passwd, tel,addr, gender, birthday);
		User user = new User(userName, passwd, addr, tel, gender, work, birthday);

		String queryRes = userService.checkTel(tel);
		if (queryRes == null) {
			int res = userService.insertSelective(user);
			System.out.println("---------res: " + res);
			obj.put("msg", "用户 [" + userName + "] 注册成功");
			obj.put("code", "200");
		} else {
			obj.put("msg", "手机号 [" + tel + "] 已注册");
			obj.put("code", "400");
		}
		response.getWriter().append(obj.toString());
	}

	// 插入用户
	@RequestMapping("/addUser")
	public void insertUser(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ParseException {
//			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		JSONObject obj = new JSONObject();

		String userName = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String tel = request.getParameter("tel");
		String birthday = request.getParameter("birthday");
		String addr = request.getParameter("addr");
		String gender = request.getParameter("gender");
		String work = null;

		String year = String.valueOf(date.get(Calendar.YEAR));
		String nMonth = String.valueOf(date.get(Calendar.MONTH));
		String nDay = String.valueOf(date.get(Calendar.DATE));
		int age = Integer.parseInt(year) - Integer.parseInt(birthday.split("-")[0]);// 当前年份-出生年份
		int month = Integer.parseInt(nMonth) - Integer.parseInt(birthday.split("-")[1]);// 当前月份-出生月份
		int day = Integer.parseInt(nDay) - Integer.parseInt(birthday.split("-")[2]);// 当前日-出生日
		if (month < 0) {
			age += 1;
		} else if (month == 0) {
			if (day < 0) {
				age += 1;
			}
		}

		System.out.println("---****------" + userName + " : " + passwd + " : " + tel + " : " + birthday + " : " + age
				+ " : " + gender + " : " + addr);
//			User user = new User(userName, passwd, age,addr, tel, gender, birthday);
		User user = new User(userName, passwd, addr, tel, gender, work, birthday);

		String queryRes = userService.checkTel(tel);
		if (queryRes == null) {
			int res = userService.insertSelective(user);
			System.out.println("---------res: " + res);
			obj.put("msg", "用户 [" + userName + "] 添加成功");
			obj.put("code", "200");
		} else {
			obj.put("msg", "用户 [" + userName + "] 已存在");
			obj.put("code", "400");
		}
		response.getWriter().append(obj.toString());
	}

	// 删除
	@RequestMapping("/delUser")
	public void delUser(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String delId = request.getParameter("id");
//		String delId = "1";
		System.out.println("---------------id: " + delId);
		List<User> user = userService.selectByPrimaryKey(Integer.parseInt(delId));
		System.out.println("---------------user: " + user);
		JSONObject obj = new JSONObject();

		if (user.size() <= 0) {
			obj.put("status", "error");
			obj.put("msg", "用户ID [" + delId + "] 不存在");
			obj.put("code", "400");
			response.getWriter().append(obj.toString());
		} else {
			if (userService.deleteByPrimaryKey(Integer.parseInt(delId)) == 1) {
				obj.put("msg", "删除成功");
				obj.put("code", "200");
				response.getWriter().append(obj.toString());
			} else {
				obj.put("status", "error");
				obj.put("msg", "其他错误");
				obj.put("code", "400");
				response.getWriter().append(obj.toString());
			}
		}
	}

	// 数据总数
	@RequestMapping("allCount")
	public void allCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int allCount = userService.allCount();
		JSONObject obj = new JSONObject();
		obj.put("status", "error");
		obj.put("allCount", allCount);
		obj.put("code", "400");
		response.getWriter().append(obj.toString());
	}

//	修改数据
	@RequestMapping("updateUser")
	public void updateUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer t_id = Integer.parseInt(request.getParameter("id"));
		String username = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String addr = request.getParameter("addr");
		String birthday = request.getParameter("birthday");
		String tel = request.getParameter("tel");
		String gender = request.getParameter("gender");
		String work = request.getParameter("work");

		JSONObject obj = new JSONObject();

//		System.out.println("userName: "+userName);
		System.out.println(
				"---------" + username + " : " + passwd + " : " + tel + " : " + birthday + " : " + " : " + gender);

		User user = new User(t_id, username, passwd, addr, tel, gender, work, birthday);
		int res = userService.updateByPrimaryKeySelective(user);
		System.out.println("----res: " + res);

		if (res != 1) {
			obj.put("msg", "修改失败");
			obj.put("code", "400");
			response.getWriter().append(obj.toString());
		} else {
			obj.put("msg", "修改成功");
			obj.put("code", "200");
			response.getWriter().append(obj.toString());
		}
//		
//		String queryRes = userService.selectByName(username);
//		if (queryRes == null) {
//			User user = new User(t_id, username, passwd, addr, tel, gender, work, birthday);
//			int res = userService.updateByPrimaryKeySelective(user);
//			System.out.println("----res: " + res);
//
//			if (res != 1) {
//				obj.put("msg", "修改失败");
//				obj.put("code", "400");
//				response.getWriter().append(obj.toString());
//			} else {
//				obj.put("msg", "修改成功");
//				obj.put("code", "200");
//				response.getWriter().append(obj.toString());
//			}
//		} else {
//			obj.put("msg", "修改失败，用户 [" + username + "] 已存在");
//			obj.put("code", "400");
//		}
//		response.getWriter().append(obj.toString());
	}

	@ResponseBody
	@RequestMapping("/uploadFile")
	public void upload(@RequestParam(value = "files") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		OutputStream os = null;
		InputStream is = null;
		String id = "";
		String userName = request.getParameter("name");
		System.out.println("=========================================name: " + userName);
//		String userName = request.getParameter("userName");
//		String passwd = request.getParameter("passwd"); // 传过来的额外参数
//		String age = request.getParameter("age");
////		String userAddr = request.getParameter("useAddr");
//		String tel = request.getParameter("tel");
//		String gender = request.getParameter("gender");
		String imgName = "";
		String imgAddr = "";
//
//		System.out.println(
//				"----------data:" + "id:" + id + "&userName:" + userName + "&password:" + passwd + "&company:" + "&age:"
//						+ age + "&gender:" + gender + "&tel:" + tel + "&imgName:" + imgName + "&imgAddr:" + imgAddr);

		JSONObject obj = new JSONObject();

//		String pathTemp = "";

		// 获取Tomcat服务器所在的路径
//		String path = request.getSession().getServletContext().getRealPath("/");
		String path = "E:\\";
		System.out.println("----------------------path:" + path);

		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			String currentDate = df.format(System.currentTimeMillis());
			System.out.println("date: " + currentDate + "name: " + userName);
			if (userName == null || userName == "" || userName.length() == 0) {
				imgAddr = path + File.separator + "upload" + File.separator + "images" + File.separator + currentDate;
			} else {
				imgAddr = path + File.separator + "upload" + File.separator + "images" + File.separator + userName;
			}
			System.out.println("------pathTemp: " + imgAddr);

			File fileTemp = new File(imgAddr);
			if (!fileTemp.exists()) {
				fileTemp.mkdirs();
			}
			imgName = file.getOriginalFilename();
			String fullFilePath = imgAddr + File.separator + imgName;
			System.out.println("------fullFilePath: " + fullFilePath);
			File fileCheck = new File(fullFilePath);
			if (fileCheck.exists() && false) {
				obj.put("code", "400");
				obj.put("msg", "文件已存在");
				response.getWriter().append(obj.toString());
				// return;
			} else {
				File fullFile = new File(fullFilePath);

				os = new FileOutputStream(fullFile);
				is = file.getInputStream();
				byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
				int length = 0;
				while ((length = is.read(buf)) > 0) {
					os.write(buf, 0, length);
				}
				obj.put("code", "200");
				obj.put("msg", "文件上传成功");
				response.getWriter().append(obj.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// return JSONObject.fromObject("{\"success\":" + returnBoolean +
		// "}").toString();
	}

	@RequestMapping("/send2")
	@ResponseBody
	protected void CalculateGeoServlet(HttpServletRequest request, HttpServletResponse response, String params)
			throws ServletException, IOException, MalformedURLException {
		ArrayList<String> fileList = new ArrayList<String>();
		JSONObject obj = new JSONObject();

		String request_path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ "/upload/images/huacx";
//		String img_name = request_path + "/pic_file/";
		System.out.println("-----------request_path： " + request_path);
		ArrayList<String> retData = new ArrayList<String>();

		// 或者直接用下面的相对路径封装
		for (String str : fileList) {
//			System.out.println("*******************str: " + str);
			retData.add(request_path + str);
		}
//		String img_name2 = "../pic_file/";

		fileList = getFiles("E:\\uploadImg\\images\\huacx");
		obj.put("code", "400");
		obj.put("msg", "ok");
		obj.put("imgArr", retData);
		response.getWriter().append(obj.toString());
		// return fileList;
	}

	@RequestMapping("/addImgSrc")
	public void addImgSrc(HttpServletRequest request, HttpServletResponse response) {
		String path = "D:\\Tomcat 8.5\\webapps\\upload\\images\\张天爱";
		String netpath = "http://localhost:8080/upload/images/张天爱/";
		getImgSrc(path, netpath, 100000001);
	}

	public void getImgSrc(String relpath, String netpath, long num) {
		String imgSrcVal = "";
		Map mp = new HashMap();
		int level = 0;
		int i_id = 2;
		File file = new File(relpath);
		File[] files = file.listFiles();

		DateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar calendar = Calendar.getInstance();
		String dateName = df1.format(calendar.getTime());
		for (File f : files) {
			if (f.isDirectory()) {
				imgSrcVal = f.getAbsolutePath();
				System.out.println("dir src: " + imgSrcVal);
				String[] arr = imgSrcVal.split("\\\\");

				relpath = imgSrcVal;
				System.out.println("----------dir-relPath： " + imgSrcVal);
				System.out.println("----------dir-netPath： " + netpath);
				getImgSrc(relpath, netpath, num++);
			} else {
				imgSrcVal = relpath + "\\" + f.getName();
				String[] arr = imgSrcVal.split("\\\\");
				String tmpPath2 = netpath + arr[arr.length - 2] + "/" + arr[arr.length - 1];
				System.out.println("----------file-relPath： " + imgSrcVal);
				System.out.println("----------file-netPath： " + tmpPath2);
				String tString = 15 + "" + num;
				System.out.println("telc: " + 15 + num);
				mp.clear();
				mp.put("tel", "15100000146");
				mp.put("level", level);
				mp.put("update", dateName);
				mp.put("realaddr", imgSrcVal);
				mp.put("netaddr", tmpPath2);
				userService.addImgSrc(mp);
			}
//			}
		}

	}

	/** * 通过递归得到某一路径下所有的目录及其文件 * @param filePath 文件路径 * @return */
	public static ArrayList<String> getFiles(String filePath) {
		ArrayList<String> fileList = new ArrayList<String>();
		File root = new File(filePath);
		File[] files = root.listFiles();
		System.out.println("--------------files: " + files.length);
		for (File file : files) {
			if (file.isDirectory()) {
				/* * 递归调用 */
				getFiles(file.getAbsolutePath());
//				fileList.add(file.getAbsolutePath());
				fileList.add(file.getName());
			} else {
				String picPathStr = file.getName();
				System.out.println("--------picPathStr: " + picPathStr);
				// String picPathStr =
				// file.getAbsolutePath().replaceAll("\\\\","//");
				fileList.add(picPathStr);
			}
		}
		for (String str : fileList) {
			System.out.println("*******************str: " + str);
		}
		return fileList;
	}

	@RequestMapping("/getImgList")
	public void getImgList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();
		List li = new ArrayList();
		List<com.huacx.model.File> res = userService.getImgList();
		for (int i = 0; i < res.size(); i++) {
			Map mp = new HashMap();
			System.out.println("-----------res.get(i).toString(): " + res.get(i).toString());
			String tel = res.get(i).getiId();
			String name = res.get(i).getName();
			int level = res.get(i).getLevel();
			String uploaddate = res.get(i).getUploaddate();
			String realaddr = res.get(i).getRealaddr();
			String netaddr = res.get(i).getNetaddr();
			mp.put("realaddr", realaddr);
			mp.put("netaddr", netaddr);
			mp.put("uploaddate", uploaddate);
			mp.put("tel", tel);
			mp.put("name", name);
			mp.put("level", level);
			System.out.println("-----mp: " + mp.toString());
			li.add(mp);
		}

		System.out.println("----------li: " + li.toString());
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	@RequestMapping("/getImgListByName")
	public void getImgListByName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();
		List li = new ArrayList();
		String searchName = request.getParameter("name");
		System.out.println("name: " + searchName);
		List<com.huacx.model.File> res = userService.getImgListByName(searchName);
		for (int i = 0; i < res.size(); i++) {
			Map mp = new HashMap();
			System.out.println("-----------res.get(i).toString(): " + res.get(i).toString());
			String tel = res.get(i).getiId();
			String name = res.get(i).getName();
			int level = res.get(i).getLevel();
			String uploaddate = res.get(i).getUploaddate();
			String netaddr = res.get(i).getNetaddr();
			mp.put("netaddr", netaddr);
			mp.put("uploaddate", uploaddate);
			mp.put("tel", tel);
			mp.put("name", name);
			mp.put("level", level);
			li.add(mp);
		}

		System.out.println("----------li: " + li.toString());
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}
	
	
	@RequestMapping("/getImgListByNameGroup")
	public void getImgListByNameGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();
		List li = new ArrayList();
		String searchName = request.getParameter("name");
		System.out.println("name: " + searchName);
		List<com.huacx.model.File> res = userService.getImgListByNameGroup(searchName);
		for (int i = 0; i < res.size(); i++) {
			Map mp = new HashMap();
			System.out.println("-----------res.get(i).toString(): " + res.get(i).toString());
			String tel = res.get(i).getiId();
			String name = res.get(i).getName();
			int level = res.get(i).getLevel();
			String uploaddate = res.get(i).getUploaddate();
			String netaddr = res.get(i).getNetaddr();
			mp.put("netaddr", netaddr);
			mp.put("uploaddate", uploaddate);
			mp.put("tel", tel);
			mp.put("name", name);
			mp.put("level", level);
			li.add(mp);
		}

		System.out.println("----------li: " + li.toString());
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	@RequestMapping("/getImgListByGroup")
	public void getImgListByGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();
		List li = new ArrayList();
		List<com.huacx.model.File> res = userService.getImgListByGroup();
		for (int i = 0; i < res.size(); i++) {
			Map mp = new HashMap();
			System.out.println("-----------res.get(i).toString(): " + res.get(i).toString());
			String tel = res.get(i).getiId();
			String name = res.get(i).getName();
			int level = res.get(i).getLevel();
			String uploaddate = res.get(i).getUploaddate();
			String netaddr = res.get(i).getNetaddr();
			mp.put("netaddr", netaddr);
			mp.put("uploaddate", uploaddate);
			mp.put("tel", tel);
			mp.put("name", name);
			mp.put("level", level);
			li.add(mp);
		}

		System.out.println("----------li: " + li.toString());
		obj.put("data", li);
		obj.put("msg", "OK");
		obj.put("code", "200");
		response.getWriter().append(obj.toString());
	}

	@RequestMapping("/upload")
	public void uploadFile(@RequestParam(value = "files") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		OutputStream os = null;
		InputStream is = null;
		String userName = request.getParameter("name");
		String tel = request.getParameter("tel");
		int level = 1;
		level = Integer.parseInt(request.getParameter("level"));
		System.out.println("------name: " + userName + " tel: " + tel);
		String imgName = "";
		String imgAddr = "";
		String netAddr = "";
		Map mp = new HashMap();
		JSONObject obj = new JSONObject();

		String relpath = "D:\\Tomcat 8.5\\webapps\\upload\\images";
		String netpath = "http://localhost:8080/upload/images/";
		System.out.println("----------------------path:" + netpath);

		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			String currentDate = df.format(System.currentTimeMillis());
			System.out.println("date: " + currentDate + "name: " + userName);

			DateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
			Calendar calendar = Calendar.getInstance();
			String dateName = df1.format(calendar.getTime());
			if (userName == null || userName == "" || userName.length() == 0) {
//				imgAddr = relpath + File.separator + "upload" + File.separator + "images" + File.separator + currentDate;
				imgAddr = relpath + File.separator + currentDate;
				netAddr = netpath + currentDate;
			} else {
//				imgAddr = relpath + File.separator + "upload" + File.separator + "images" + File.separator + userName;
				imgAddr = relpath + File.separator + userName;
				netAddr = netpath + userName;
			}
			System.out.println("------realAddr: " + imgAddr);
			System.out.println("------netAddr: " + netAddr);

			File fileTemp = new File(imgAddr);
			if (!fileTemp.exists()) {
				fileTemp.mkdirs();
			}
			imgName = file.getOriginalFilename();
			String fullFilePath = imgAddr + File.separator + imgName;
			System.out.println("------fullFilePath: " + fullFilePath);
			File fullFile = new File(fullFilePath);

			os = new FileOutputStream(fullFile);
			is = file.getInputStream();
			byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
			int length = 0;
			while ((length = is.read(buf)) > 0) {
				os.write(buf, 0, length);
			}

			mp.put("tel", tel);
			mp.put("level", level);
			mp.put("update", dateName);
			mp.put("name", userName);
			mp.put("realaddr", fullFilePath);
			mp.put("netaddr", netAddr + "/" + imgName);
			userService.addImgSrc(mp);
			System.out.println(mp.toString());
			obj.put("code", "200");
			obj.put("msg", "文件[" + imgName + "]上传成功");
			response.getWriter().append(obj.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@RequestMapping("/delImg")
	public void delImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String url = request.getParameter("url");
		String uploaddate = request.getParameter("uploaddate");
//		Integer integer = userService.delImg(url);
		Map smp = new HashMap();
		smp.put("netaddr", url);
		smp.put("uploaddate", uploaddate);
		String path = userService.getRealAddr(smp);
		System.out.println("path: "+path);
		File f = new File(path);
		f.delete();
		JSONObject obj = new JSONObject();
		if (userService.delImg(smp) == 1) {
			obj.put("msg", "删除成功");
			obj.put("code", "200");
			response.getWriter().append(obj.toString());
		} else {
			obj.put("status", "error");
			obj.put("msg", "删除失败");
			obj.put("code", "400");
			response.getWriter().append(obj.toString());
		}
	}
}
